<?php

/*
 * Парсим картинки для OpenCart.
 * 
 * eosagm@gmail.com
 * 
 * icq# 217861501
 * 
 * 
 */

class ModelToolParseImage extends Model {

    private $product;
    private $facade;

    public function __construct($registry) {



        parent::__construct($registry);
        $this->registry->get('load')->library('parseImage/parseImage');
        $this->registry->get('load')->library('parseImage/simple_html_dom');

        $this->load->model('catalog/product');
        $this->facade = new pFacade();
        $this->product = array();
        $this->product['img_link'] = array();
    }

    public function insertImage($img_link, $id = 0) {

        $filename = 'data/' . $this->facade->downloadImage($img_link);

        if ($id !== 0) {
            $this->db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int) $id . "', image = '" . $this->db->escape(html_entity_decode($filename, ENT_QUOTES, 'UTF-8')) . "', sort_order = ''");
        }
    }

    public function getProduct($id = 0, $searchtext = "") {


        if (!empty($searchtext) && !empty($id)) {

            $this->product['product_id'] = (int) $id;

            $product = $this->model_catalog_product->getProduct((int) $id);
            $this->product['name'] = $product['name'];
        } else {
            $this->getNoImage($id);
            $searchtext = $this->product['name'];
        }

        $this->product['img_link'] = $this->facade->parseYandex((string) $searchtext);

        $this->product['next'] = $this->url->link('module/parseimage&id=' . $this->product['product_id'], 'token=' . $this->session->data['token'], 'SSL');

        return $this->product;
    }



    private function getNoImage($id = 0) {


        $products = $this->model_catalog_product->getProducts();

        foreach ($products as $product) {

            if (!empty($product['product_id']) && (int) $product['product_id'] > (int) $id) {
                $images = $this->model_catalog_product->getProductImages((int) $product['product_id']);

                if (empty($images)) {
                    $this->product['name'] = $product['name'];
                    $this->product['product_id'] = (int) $product['product_id'];
                    return;
                }
            }
        }
    }

}

?>
